#include "activation_thread.h"
#include "receive_dbus.h"
#include <QDebug>

activation_thread::activation_thread(QObject *parent) : QThread(parent)
{

}

void activation_thread::run()
{
    //循环监听usb的激活ukey插入，并自动进行激活。
//    qDebug() << "ukey check!";
//    gint activation= 1;
//    struct sockaddr_nl client;
//    struct timeval tv;
//    char buf[UEVENT_BUFFER_SIZE] = { 0 };
//    int CppLive, rcvlen, ret, flag=1;
//    fd_set fds;
//    int buffersize = 1024;
//    CppLive = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
//    memset(&client, 0, sizeof(client));
//    client.nl_family = AF_NETLINK;
//    client.nl_pid = getpid();
//    client.nl_groups = 1; /* receive broadcast message*/
//    setsockopt(CppLive, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
//    bind(CppLive, (struct sockaddr*)&client, sizeof(client));
//    while (1) {
//        sleep(1);
//        if(flag)
//        {
//            flag = 0;
//            activation=active_code("");
//            emit signal_ukey_activation(activation); //默认调用一次ukey激活
//        }
//        memset(buf, 0, sizeof(buf));
//        FD_ZERO(&fds);
//        FD_SET(CppLive, &fds);
//        tv.tv_sec = 0;
//        tv.tv_usec = 100 * 1000;
//        ret = select(CppLive + 1, &fds, NULL, NULL, &tv);
//        if(ret < 0)
//           continue;
//        if(!(ret > 0 && FD_ISSET(CppLive, &fds)))
//           continue;
//        /* receive data */
//        rcvlen = recv(CppLive, &buf, sizeof(buf), 0);
//        if (rcvlen > 0) {
//            if(rcvlen)
//            {
                int activation=active_code("");
                emit signal_ukey_activation(activation);
//            }

//        }
//    }

}

ukey_find_thread::ukey_find_thread(QObject *parent) : QThread(parent)
{
    nameownerchange = false;
    ukey_check_timer = new QTimer;
    connect(ukey_check_timer,SIGNAL(timeout()),this,SLOT(ukey_ckeck()));

    QDBusConnection::systemBus().connect(QString("org.freedesktop.DBus"), QString("/org/freedesktop/DBus"),
                                             QString("org.freedesktop.DBus"),
                                             QString("NameOwnerChanged"), this, SLOT(nameownerchanged(QString,QString,QString)));
}

void ukey_find_thread::run()
{
    qDebug()<<"ukey_find_thread run";
}

void ukey_find_thread::ukey_ckeck()
{
    if (nameownerchange) {
        nameownerchange = false;
        gint ukey = find_ukey();
        qDebug()<<"ukey check result"<<ukey;
        ukey_ckeck_result(ukey);
    }
}
void ukey_find_thread::nameownerchanged(QString a, QString b, QString c)
{
    nameownerchange = true;
}
